package com.kakahair.plat.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.kakahair.common.controller.BaseController;
import com.kakahair.common.util.AjaxResponse;
import com.kakahair.common.util.SessionUtil;
import com.kakahair.plat.entity.Order;
import com.kakahair.plat.entity.User;
import com.kakahair.plat.service.OrderService;
import com.kakahair.plat.service.UserService;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Tiddar
 * @since 2018-04-07
 */
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {
	@Autowired
	private UserService userService;

	@PostMapping("/login")
	public AjaxResponse login(@RequestBody User user) {
		AjaxResponse res = AjaxResponse.instance();
		try {
			user.setLastLoginTime(new Date());
			logger.debug("用户尝试登录" + user);
			SessionUtil.setLoginUser(request, user);
			userService.insertOrUpdate(user);
			logger.debug("用户" + user.getOpenid() + user.getNickName() + "登录成功");
			Map<String, String> data = new HashMap<String, String>();
			data.put("sessionId", request.getSession().getId());
			res.setSuccess(true);
			res.setMessage("登录成功");
			res.setData(data);
		} catch (Exception e) {
			logger.error("登录失败", e.fillInStackTrace());
			res.setSuccess(false);
			res.setMessage("登录失败" + e.getMessage());
		}
		return res;
	}

	@GetMapping("/userinfo")
	public AjaxResponse getUserInfo(String openid) {
		AjaxResponse res = AjaxResponse.instance();
		try {
			User user = userService.selectById(openid);
			if(null == user ) res.fail(null, "获取用户信息失败");
			else res.ok(user, "获取用户信息成功");
		} catch (Exception e) {
			// TODO: handle exception
			res.fail(e,"获取失败");	
		}
		return res;
	}
}